#ifndef __M_UTIL
#define __M_UTIL

#include <iostream>
#include <ctime>
#include <unistd.h>
#include <sys/stat.h>

namespace nhylog
{
    namespace util
    {
        class Date
        {
        public:
            static size_t now()
            {
                return (size_t)time(nullptr);
            }
        };

        class File
        {
        public:
            // 文件是否存在
            static bool exists(const std::string &pathname)
            {
                // 不具备可移植性
                // return access(pathname.c_str(),F_OK) == 0;

                struct stat st;
                if (stat(pathname.c_str(), &st) < 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }

            // 获取文件所在路径
            static std::string path(const std::string &pathname)
            {
                size_t pos = pathname.find_last_of("/\\");
                if (std::string::npos == pos)
                {
                    return ".";
                }
                else
                {
                    return pathname.substr(0, pos + 1);
                }
            }

            // 创建目录
            static void createDirectory(const std::string &pathname)
            {
                size_t pos = 0, idx = 0;

                while (idx < pathname.size())
                {
                    pos = pathname.find_first_of("/\\", idx);
                    if (std::string::npos == pos)
                    {
                        mkdir(pathname.c_str(), 0777);
                    }
                    std::string parent_dir = pathname.substr(0, pos + 1);

                    // if(parent_dir == "." || parent_dir == "..")
                    if (exists(pathname))
                    {
                        idx = pos + 1;
                        continue;
                    }
                    else
                    {
                        mkdir(parent_dir.c_str(), 0777);
                        idx = pos + 1;
                    }
                }
            }
        };
    }

}


#endif
